import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { checkout } from '../actions'
import { getTotal, getCartProducts } from '../reducers'
import Cart from '../components/Cart'

//三个参数通过connect初始化命令时，初始化传入
const CartContainer = ({ products, total, checkout }) => (
  <Cart
    products={products}
    total={total}
    onCheckoutClicked={() => checkout(products)} />
)

CartContainer.propTypes = {
  products: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.number.isRequired,
    title: PropTypes.string.isRequired,
    price: PropTypes.number.isRequired,
    quantity: PropTypes.number.isRequired
  })).isRequired,
  total: PropTypes.string,
  checkout: PropTypes.func.isRequired
}

// const mapStateToProps = (state) => ({
//   products: getCartProducts(state),
//   total: getTotal(state)
// })
//const声明一个变量为方法，变量指向的方法为引用，返回的数据不一样而且
//不存在做重新赋值操作，该变量一直指向为mapStateToProps方法
const mapStateToProps = function mapStateToProps(state) {
    return {
        products: getCartProducts(state),
        total: getTotal(state)
    };
};
//调用redux的connect方法，给CartContainer（props）传入参数，通过Object.assign()合并参数
//返回一个通过redux包裹的组件
//connect的源码实现为connect(props, actions){return function(WrappedComponent){}}
//connect返回一个方法，然后调用该方法，props，actions均为对象
export default connect(
  mapStateToProps,
  { checkout }
)(CartContainer)
